package com.xs.shop.user.service.interceptors;

import com.xs.shop.common.exceptions.BusinessException;
import com.xs.shop.common.exceptions.enums.Resp;
import com.xs.shop.user.service.handlers.BaseContextHandler;
import com.xs.shop.user.service.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Resource
    private JwtUtil jwtUtil;

    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
        long tid = Thread.currentThread().getId();
        log.info("AuthorizationInterceptor preHandle id:{}", tid);
        log.info("uri:{}", request.getRequestURI());
        // 从请求头获取token
        String token = request.getHeader("Authorization");
        log.info("token:{}", token);

        if(token == null || token.equals("")){
            throw new BusinessException(Resp.TOKEN_MISSING);
        }

        token = token.replace("Bearer ","");
        Claims claims = jwtUtil.parseAccessToken(token);
        //todo 0717 增加解析memberId的逻辑
        Long id = claims.get("adminId", Long.class);
        if(id == null){
            id = claims.get("memberId",Long.class);
        }
        log.info("id:{}",id);
        BaseContextHandler.set(id);
        return true;
    }
}
